package cn.demoncat.util.io;

import cn.demoncat.util.lang.entity.ListStr;
import org.patchca.color.ColorFactory;
import org.patchca.color.SingleColorFactory;
import org.patchca.filter.predefined.CurvesRippleFilterFactory;
import org.patchca.font.RandomFontFactory;
import org.patchca.service.ConfigurableCaptchaService;
import org.patchca.utils.encoder.EncoderHelper;
import org.patchca.word.AdaptiveRandomWordFactory;
import org.patchca.word.RandomWordFactory;

import java.awt.*;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

/**
 * Patchca 图片验证码处理工具
 *
 * @author 延晓磊
 *
 * @since 2017年7月22日
 */
public class PatchcaUtil {

	//验证码
	private static final String NUM_CODES = "123456789";
	private static final String APH_CODES = "23456789abcdefghjkmnpqrstuvwsyzABCDEFGHJKLMNPQRSTUVWSYZ";
	//字体
	private static final List<String> FAMILY = ListStr.getInstance("Tahoma","Verdana");
	//颜色
	private static final ColorFactory COLOR = new SingleColorFactory(new Color(25, 60, 170));
	//图片类型
	private static final String TYPE = "png";
	//宽高,字号
	private static final int WIDTH = 100;
	private static final int HEIGHT = 45;
	private static final int SIZE = 8;
	
	//Patchca配置
	private static ConfigurableCaptchaService config = null;

	/**
	 * 输出验证码图片，返回验证码
	 * 
	 * @param isOnlyNumber
	 *            是否只包含数字
	 * @param length
	 *            验证码长度
	 * @param os
	 *            输出流（输出后将关闭）
	 * @return
	 */
	public static String out(boolean isOnlyNumber, int length, OutputStream os) {
		//配置验证码
		ConfigurableCaptchaService config = getConfig();
		// 添加验证码
		if (isOnlyNumber) {
			RandomWordFactory t = new RandomWordFactory();
			t.setCharacters(NUM_CODES);
			t.setMaxLength(length);
			t.setMinLength(length);
			config.setWordFactory(t);
		} else {
			AdaptiveRandomWordFactory t = new AdaptiveRandomWordFactory();
			t.setCharacters(APH_CODES);
			t.setMaxLength(length);
			t.setMinLength(length);
			config.setWordFactory(t);
		}
		// 输出图片，返回验证码
		try {
			return EncoderHelper.getChallangeAndWriteImage(config, TYPE, os);
		} catch (IOException e) {
			throw new RuntimeException("生成图片验证码失败：" + e.getMessage(), e);
		} finally {
			try {
				os.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 
	 * 功能描述：配置/获取图片样式
	 *
	 * @return
	 * 
	 * @author 延晓磊
	 *
	 * @since 2017年7月22日
	 */
	private static ConfigurableCaptchaService getConfig(){
		if (config == null) {
			// 绘制图片
			config = new ConfigurableCaptchaService();
			config.setColorFactory(COLOR);
			RandomFontFactory r = new RandomFontFactory();
			r.setMaxSize(SIZE);
			r.setRandomStyle(true);
			r.setFamilies(FAMILY);
			config.setFontFactory(r);
			config.setFilterFactory(new CurvesRippleFilterFactory(config.getColorFactory()));
			config.setWidth(WIDTH);
			config.setHeight(HEIGHT);
			config.setColorFactory(COLOR);
		}
		return config;
	}

}
